package com.mm.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mm.constant.BusinessConstant;
import com.mm.dao.ResumeMapper;
import com.mm.exception.ServiceException;
import com.mm.model.Resume;
import com.mm.service.ResumeService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 个人简历service实现类
 *
 * @date 2018/7/18 18:40
 */
@Service(value = "resumeService")
public class ResumeServiceImpl implements ResumeService {
	@Autowired
	private ResumeMapper resumeMapper;

	/**
	 * 保存个人简历
	 *
	 * @param jsonData String(JSON字符串)
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveResume(String jsonData) throws ServiceException {
		if (StringUtils.isBlank(jsonData)) {
			throw new ServiceException("输入参数不能为空");
		}
		JSONObject dataJsonObj = JSON.parseObject(jsonData);
		//获取个人简历字符串
		String resumeJsonString = dataJsonObj.getString(BusinessConstant.JSON_KEY_RESUME);
		if (StringUtils.isBlank(resumeJsonString)) {
			//转化为Resume对象
			Resume resume = JSON.parseObject(resumeJsonString, Resume.class);
			//保存Resume
			resumeMapper.insertResume(resume);
			//获取个人简历关联图片ID
			String pictureIds = dataJsonObj.getString(BusinessConstant.JSON_KEY_PICTURE_IDS);
			if (StringUtils.isNotBlank(pictureIds)) {
				//保存个人简历图片关系
				saveResumePicture(resume.getResumeId(), pictureIds);
			}
		}
	}

	/**
	 * 更新个人简历
	 *
	 * @param resume Resume
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void updateResume(Resume resume) {
		if (resume != null) {
			resumeMapper.updateResumeById(resume);
		}
	}

	/**
	 * 获取个人简历
	 *
	 * @param resumeId 个人简历ID
	 * @return Resume
	 */
	@Override
	@Transactional(readOnly = true, rollbackFor = Exception.class)
	public Resume getOneResumeById(Long resumeId) {
		if (resumeId == null) {
			return null;
		}
		return resumeMapper.getOneResumeById(resumeId);
	}

	/**
	 * 通过个人简历ID删除个人简历
	 *
	 * @param resumeId 个人简历ID
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void deleteResumeById(Long resumeId) {
		if (resumeId != null) {
			resumeMapper.deleteResumeById(resumeId);
		}
	}

	/**
	 * @param resumeId   个人简历ID
	 * @param pictureIds 图片ID字符串（ID之间以“，”分割）
	 */
	@Override
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void saveResumePicture(Long resumeId, String pictureIds) throws ServiceException {
		if (resumeId == null || StringUtils.isBlank(pictureIds)) {
			throw new ServiceException("输入参数不能为空");
		}
		String[] pictureIdArray = pictureIds.split(",");
		resumeMapper.insertResumePicture(resumeId, pictureIdArray);
	}
}
